<template>
    <el-dialog :visible.sync="visible" width="900px" :show-close="false" class="scm-product-dialog">
      <!-- 1. 标题栏 -->
      <div style="font-weight: bold; font-size: 22px; color: #222; text-align: center; margin-bottom: 10px;">
        选择引用数据
      </div>
  
      <!-- 2. 标签页 -->
      <el-tabs v-model="activeTab" style="margin-bottom: 10px;">
        <el-tab-pane label="待选" name="toSelect"></el-tab-pane>
        <el-tab-pane label="已选" name="selected"></el-tab-pane>
      </el-tabs>
  
      <!-- 3. 搜索框和新增按钮 -->
      <div style="display: flex; justify-content: flex-end; align-items: center; margin-bottom: 10px;">
        <el-input
          v-model="search"
          placeholder="按 enter 键搜索"
          clearable
          style="width: 240px;"
          @keyup.enter.native="handleSearch"
        />
        <el-button type="primary" style="margin-left: 10px;" @click="handleAdd">新增数据</el-button>
      </div>
  
      <!-- 5. 数据表格 -->
      <el-table
        :data="displayTableData"
        border
        style="width: 100%;"
        v-loading="loading"
        height="350"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'id', order: 'descending' }"
        :row-key="row => row.id"
        ref="elTable"
      >
        <el-table-column
          v-if="activeTab === 'toSelect'"
          type="selection"
          width="50"
        />
        <el-table-column prop="id" label="编号" sortable />
        <el-table-column prop="drawingNumber" label="图号" sortable />
        <el-table-column prop="version" label="版本号" sortable />
        <el-table-column prop="internalVersion" label="内部版本号" sortable />
        <el-table-column prop="productName" label="产品名称" sortable />
        <el-table-column prop="model" label="型号" sortable />
        <el-table-column prop="color" label="颜色" sortable />
        <el-table-column prop="massUnit" label="量产单位" sortable />
        <el-table-column prop="massUnitPrice" label="量产单价" sortable />
      </el-table>
  
      <!-- 6. 分页控件 -->
      <div v-if="activeTab === 'toSelect'" style="display: flex; justify-content: space-between; align-items: center; margin: 16px 0 0 0;">
        <div style="color: #888;">
          已选 {{ selectedRows.length }} / 共 {{ total }} 条数据
        </div>
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
      <div v-else style="color: #888; margin: 16px 0 0 0;">
        已选 {{ selectedRows.length }} 条数据
      </div>
  
      <!-- 7. 操作按钮区 -->
      <div slot="footer" class="dialog-footer" style="text-align: right; border-top: 1px solid #eee; padding-top: 16px; margin-top: 10px;">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="warning" style="background: orange; color: #fff; border: none;" @click="handleConfirm">确认</el-button>
      </div>
    </el-dialog>
  </template>
  
  <script>
  import { listScmProducts } from "@/api/scm/scmProducts";
  
  export default {
    name: "ScmProductList",
    props: {
      visible: Boolean
    },
    data() {
      return {
        activeTab: "toSelect",
        search: "",
        loading: false,
        currentPage: 1,
        pageSize: 50,
        total: 0,
        selectedRows: [],
        allData: [],
        selectedMap: {} // 用于全局保存已选项
      };
    },
    computed: {
      tableData() {
        // 搜索和分页
        let filtered = this.allData.filter(item =>
          !this.search ||
          (item.productName && item.productName.includes(this.search)) ||
          (item.drawingNumber && item.drawingNumber.includes(this.search)) ||
          (item.model && item.model.includes(this.search))
        );
        this.total = filtered.length;
        const start = (this.currentPage - 1) * this.pageSize;
        return filtered.slice(start, start + this.pageSize);
      },
      displayTableData() {
        // 待选tab显示tableData，已选tab显示所有已选
        if (this.activeTab === "toSelect") {
          return this.tableData;
        } else {
          return Object.values(this.selectedMap);
        }
      }
    },
    watch: {
      visible(val) {
        if (val) {
          this.currentPage = 1;
          this.fetchData();
          this.$nextTick(() => {
            if (this.activeTab === "toSelect") this.setTableSelection();
          });
        }
      },
      activeTab(val) {
        // 切换到已选时，取消表格的多选框选中状态
        if (val === "selected" && this.$refs.elTable) {
          this.$refs.elTable.clearSelection();
        }
        if (val === "toSelect" && this.$refs.elTable) {
          this.$nextTick(() => {
            this.setTableSelection();
          });
        }
      }
    },
    methods: {
      fetchData() {
        this.loading = true;
        listScmProducts({ pageNum: this.currentPage, pageSize: this.pageSize, search: this.search }).then(res => {
          this.allData = res.rows || [];
          this.total = res.total || this.allData.length;
          this.loading = false;
          this.$nextTick(() => {
            if (this.activeTab === "toSelect") this.setTableSelection();
          });
        }).catch(() => {
          this.loading = false;
        });
      },
      setTableSelection() {
        if (this.$refs.elTable) {
          this.$refs.elTable.clearSelection();
          this.tableData.forEach(row => {
            if (this.selectedMap[row.id]) {
              this.$refs.elTable.toggleRowSelection(row, true);
            }
          });
        }
      },
      handleSearch() {
        this.currentPage = 1;
        this.fetchData();
      },
      handleAdd() {
        this.$message.info("点击了新增数据");
      },
      handleSelectionChange(val) {
        // 先把当前页所有数据从 map 里移除
        this.tableData.forEach(item => {
          if (this.selectedMap[item.id]) {
            delete this.selectedMap[item.id];
          }
        });
        // 再把当前页勾选的加进去
        val.forEach(item => {
          this.selectedMap[item.id] = item;
        });
        // 更新 selectedRows
        this.selectedRows = Object.values(this.selectedMap);
      },
      handleSizeChange(size) {
        this.pageSize = size;
        this.currentPage = 1;
        this.fetchData();
      },
      handlePageChange(page) {
        this.currentPage = page;
        this.fetchData();
      },
      handleCancel() {
        this.$emit("update:visible", false);
      },
      handleConfirm() {
        this.$emit("select", this.selectedRows);
        this.$emit("update:visible", false);
      }
    }
  };
  </script>
  
  <style scoped>
  .scm-product-dialog .el-dialog__body {
    padding-top: 0;
  }
  </style>